package com.tedu.egspringbootmvc.exception;

import com.tedu.egspringbootmvc.result.JsonResult;
import com.tedu.egspringbootmvc.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandlerThrowable(Throwable e){
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException e){
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error(e.getFieldError().getDefaultMessage(),e);
        String message = e.getFieldError().getDefaultMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }

    @ExceptionHandler
    //处理单个参数（Range）
    public JsonResult doHandlerConstraintViolation(ConstraintViolationException e){
        String msg = e.getMessage();
        StringBuilder builder = new StringBuilder(msg);
        builder.delete(0,msg.indexOf(":")+2);
        log.error(builder.toString(),e);
        return new JsonResult(StatusCode.VALIDATED_ERROR,builder);
    }
}
